import { createRouter, createWebHistory } from 'vue-router'

// 从 views 中导入页面组件
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Dashboard from '../views/Dashboard.vue'
import AdminDashboard from '../views/AdminDashboard.vue'
import PostOverview from '../views/PostOverview.vue'
import UserPosts from '../views/UserPosts.vue'
import UserProfile from '../views/UserProfile.vue'
import PostDetail from '../views/PostDetail.vue'
import CreatePost from '../views/CreatePost.vue'
import HomeView from '../views/HomeView.vue'
import QnAView from '../views/QnAView.vue'


const routes = [
  { path: '/', redirect: '/home' }, // ✅ 修改默认首页指向
  { path: '/home', component: HomeView, name: 'HomeView' }, // ✅ 新增首页
  { path: '/login', component: Login, name: 'Login', meta: { title: '登录' } },
  { path: '/register', component: Register, name: 'Register', meta: { title: '注册' } },
  { path: '/dashboard', component: Dashboard, name: 'Dashboard', meta: { requiresAuth: true } },
  { path: '/admin/dashboard', component: AdminDashboard, name: 'AdminDashboard', meta: { requiresAuth: true, adminOnly: true } },
  { path: '/post/overview', component: PostOverview, name: 'PostOverview', meta: { requiresAuth: true } },
  { path: '/user/posts', component: UserPosts, name: 'UserPosts', meta: { requiresAuth: true } },
  { path: '/user/profile', component: UserProfile, name: 'UserProfile', meta: { requiresAuth: true } },
  { path: '/post/detail/:id', component: PostDetail, name: 'PostDetail' }, // 不要求登录
  { path: '/post/create', component: CreatePost, name: 'CreatePost', meta: { requiresAuth: true } },
  { path: '/qna', name: 'QnAView', component: QnAView }

]

const router = createRouter({
  history: createWebHistory(),
  routes
})
import { useUserStore } from '@/stores/user'
// 全局前置守卫
router.beforeEach((to, from, next) => {

  const userStore = useUserStore()

  console.log('进入路由守卫')
  console.log('目标路由:', to.fullPath)
  console.log('用户信息:', userStore.user)

  // 如果 Pinia 中没有 user，尝试从 localStorage 恢复
  if (!userStore.user || !userStore.user.username) {
    const localUser = localStorage.getItem('user')
    if (localUser) {
      try {
        userStore.setUser(JSON.parse(localUser))
      } catch (e) {
        console.warn('localStorage user 数据错误')
      }
    }
  }



  const user = userStore.user
  const isLoggedIn = user && user.username
  const isAdmin = isLoggedIn && user.userType === 'admin'

  if (to.meta.requiresAuth && !isLoggedIn) {
    console.warn('未登录，重定向到登录页')
    next({
      name: 'Login',
      query: { redirect: to.fullPath }
    })
    return
  }

  if (to.meta.adminOnly && !isAdmin) {
    console.warn('非管理员，重定向到用户首页')
    next({ name: 'Dashboard' })
    return
  }

  console.log('通过守卫，跳转中...')
  next()
})

export default router
